from django.shortcuts import render,redirect,HttpResponse
from app.models import Admin,Press,Book,BookType
import os
from django.views import View
#登录  查询
def login(request):

    if request.method == "GET":
        return render(request,"login.html")
    else:
        # 接收界面参数
        username = request.POST.get("username")
        password = request.POST.get("password")

        if Admin.objects.filter(username=username, password=password):
            # 登录成功  存储信息
            response = redirect("/presslist/")
            # 设置响应cookie
            #response.set_cookie("login","OK")

            # 设置session
            request.session["login"] = "ok"

            return response
        else:
            return render(request, "login.html", {"msg": "用户名或密码错误！"})


# import time
# def codeTime(fn):
#     def inner(*args, **kwargs):
#         begin = time.time()
#         a = fn(*args, **kwargs)
#         end = time.time()
#         print("代码运行时长%.2f" % (end - begin))
#         return a
#     return inner

from django.contrib import messages
# 登录装饰器
def login_decorator(fun):
    def inner(request,*args, **kwargs):
        # 先判断是否正常登录
        if request.session.get("login"):
            #如果满足，则方法正常访问
            return fun(request,*args, **kwargs)
        messages.warning(request,"登录信息已过期，请重新登录！")
        return redirect("/login/")

    return inner

@login_decorator
def pressadd(request):
    if request.method == "GET":
        return render(request,"pressadd.html")
    else:
        #接收参数   从页面出发，回归页面
        pressname = request.POST.get("pressname")
        pressaddress = request.POST.get("pressaddress")

        #调用ORM，执行添加请求
        Press.objects.create(pressname=pressname,pressaddress=pressaddress)

        # 跳转页面 出版社列表页面 重定向
        return redirect("/presslist")
from django.utils.decorators import method_decorator
# class PressAdd(View):
#
#     # @method_decorator(codeTime)
#     def dispatch(self, request, *args, **kwargs):
#         print("调用方法之前")
#
#
#
#         result = super().dispatch(request, *args, **kwargs)
#         print("调用方法之后")
#         return result
#
#
#     def get(self,request):
#         print("接收到了浏览器发送的get请求")
#         return render(request, "pressadd.html")


def presslist(request):
    request.session["login"] = "ok"


    #调用orm
    presslist = Press.objects.all()

    #跳转页面  带参数
    return render(request,"presslist.html",{"presslist":presslist})

from django.urls import reverse
@login_decorator
def pressdelete(request):
    #参数
    id = request.GET.get("id")
    #调用orm   对象状态转换
    Press.objects.filter(id=id).delete()
    # 跳转页面 出版社列表页面 重定向
    return redirect(reverse("presslist"))

@login_decorator
def pressupdate(request):

    if request.method == "GET":
        #参数
        id = request.GET.get("id")

        #调用orm   对象状态转换
        press = Press.objects.get(id=id)

        # 跳转页面 修改页面页面 转发
        return render(request,"pressupdate.html",{"press":press})
    else:
        # 真正修改功能
        # 接收页面要修改的参数 和 要修改的数据id
        id = request.POST.get("id")
        pressname = request.POST.get("pressname")
        pressaddress = request.POST.get("pressaddress")

        # 真正修改 第一步：通过id找到orm对象
        press = Press.objects.get(id=id)

        # 第二步：通过orm对象（持久化对象） 设置要修改的属性
        press.pressname = pressname
        press.pressaddress = pressaddress

        # 第三步：执行持久化方法，完成修改功能
        press.save()

        # 跳转页面 出版社列表页面 重定向
        return redirect("/presslist")

@login_decorator
def presssearch(request):
    #参数
    pressname = request.POST.get("pressname")
    #调用orm   对象状态转换
    presslist = Press.objects.filter(pressname__icontains=pressname)
    # 跳转页面 出版社列表页面 重定向
    return render(request,"presslist.html",{"presslist":presslist,"pressname":pressname})


def bookadd(request):
    if request.method == "GET":

        presslist = Press.objects.all()
        return render(request,"bookadd.html",{"presslist":presslist})
    else:
        #接收参数   从页面出发，回归页面
        bookname = request.POST.get("bookname")
        bookprice = request.POST.get("bookprice")
        bookauthor = request.POST.get("bookauthor")
        press = request.POST.get("press")

        # 获取上传之后的文件
        bookimg_obj = request.FILES.get("bookimg")

        # print( type( bookimg_obj))
        # print( type( bookimg_obj.name))

        bookimg_name = bookimg_obj.name

        # 获取文件要保存的路径
        bookimg_path = "static/img"

        # 拼接向数据库保存的图片路径及名称
        bookimg = os.path.join(bookimg_path,bookimg_name)

        # print(bookimg)
        # 文件上传 （文件从本地复制到服务器）
        with open(bookimg,"wb") as file:
            for xxx in bookimg_obj.chunks():
                file.write(xxx)

        #调用ORM，执行添加请求
        bookimg = "/"+bookimg
        Book.objects.create(bookname=bookname,bookprice=bookprice,bookauthor=bookauthor,bookimg=bookimg,press_id=press)

        # 跳转页面 出版社列表页面 重定向
        return redirect("/booklist")

def booklist(request):

    #调用orm
    booklist = Book.objects.all()

    #跳转页面  带参数
    return render(request,"booklist.html",{"booklist":booklist})

def booksearch(request):

    #参数
    bookname = request.POST.get("bookname")
    #调用orm   对象状态转换
    booklist = Book.objects.filter(bookname__icontains=bookname)
    # 跳转页面 出版社列表页面 重定向
    return render(request,"booklist.html",{"booklist":booklist,"bookname":bookname})

def bookdelete(request):
    #参数
    id = request.GET.get("id")
    #调用orm   对象状态转换
    Book.objects.filter(id=id).delete()
    # 跳转页面 出版社列表页面 重定向
    return redirect("/booklist")

def bookupdate(request):

    if request.method == "GET":
        #参数
        id = request.GET.get("id")

        #调用orm   对象状态转换
        book = Book.objects.get(id=id)
        #查询所有出版社，供添加图书页面上下拉框循环展示
        presslist = Press.objects.all()

        # 跳转页面 修改页面页面 转发
        return render(request,"bookupdate.html",{"book":book,"presslist":presslist})
    else:
        # 真正修改功能
        # 接收页面要修改的参数 和 要修改的数据id
        id = request.POST.get("id")
        bookname = request.POST.get("bookname")
        bookprice = request.POST.get("bookprice")
        bookauthor = request.POST.get("bookauthor")
        press = request.POST.get("press")


        bookimg_obj = request.FILES.get("bookimg")

        #判断bookimg_obj是否为空，如果为空，说明用户没有修改图片
        if bookimg_obj:
            bookimg_name = bookimg_obj.name
            # 获取文件要保存的路径
            bookimg_path = "static/img"
            # 拼接向数据库保存的图片路径及名称
            bookimg = os.path.join(bookimg_path, bookimg_name)
            # print(bookimg)
            # 文件上传 （文件从本地复制到服务器）
            with open(bookimg, "wb") as file:
                for xxx in bookimg_obj.chunks():
                    file.write(xxx)
            bookimg = "/" + bookimg
        else:
            bookimg = request.POST.get("bookimgname")

        # 真正修改 第一步：通过id找到orm对象
        book = Book.objects.get(id=id)

        # 第二步：通过orm对象（持久化对象） 设置要修改的属性
        book.bookname = bookname
        book.bookprice = bookprice
        book.bookauthor = bookauthor
        book.bookimg = bookimg
        book.press_id = press

        # 第三步：执行持久化方法，完成修改功能
        book.save()

        # 跳转页面 出版社列表页面 重定向
        return redirect("/booklist")

def booktypelist(request):

    #调用orm
    booktypelist = BookType.objects.all()

    print(booktypelist)

    #跳转页面  带参数
    return render(request,"booktypelist.html",{"booktypelist":booktypelist})


def booktypeadd(request):
    if request.method == "GET":

        booklist = Book.objects.all()
        return render(request,"booktypeadd.html",{"booklist":booklist})
    else:

        #接收参数   从页面出发，回归页面
        typename = request.POST.get("typename")
        bookids = request.POST.getlist("bookids")

        #调用ORM，执行添加请求
        booktype = BookType.objects.create(typename=typename)

        #设置中间表
        booktype.books.set(bookids)

        # 跳转页面 出版社列表页面 重定向
        return redirect("/booktypelist")

def booktypeupdate(request):

    if request.method == "GET":
        #参数
        id = request.GET.get("id")

        #调用orm   对象状态转换
        booktype = BookType.objects.get(id=id)
        #查询所有图书，供修改类型页面上复选框循环
        booklist = Book.objects.all()

        # 跳转页面 修改页面页面 转发
        return render(request,"booktypeupdate.html",{"booktype":booktype,"booklist":booklist})
    else:
        # 真正修改功能
        # 接收页面要修改的参数 和 要修改的数据id
        id = request.POST.get("id")
        typename = request.POST.get("typename")
        bookids = request.POST.getlist("bookids")

        # 调用ORM，执行添加请求
        update_booktype = BookType.objects.get(id=id)
        #
        # #设置中间表
        update_booktype.typename = typename
        #
        update_booktype.save()
        #
        update_booktype.books.set(bookids)

        # 跳转页面 出版社列表页面 重定向
        return redirect("/booktypelist")

def booknameisexit(request):

    bookname = request.POST.get("bookname")

    if Book.objects.filter(bookname=bookname):
        #说明存在
        return HttpResponse("OK")
    return HttpResponse("ERROR")

def index(request):

    booklist = Book.objects.all()
    return render(request,"index.html",{"booklist":booklist})


"""
    get方式：
        01：刷新浏览器地址栏
        02：a链接 href属性
        03：window.location.href
        04：form表单中，method="GET"
        05：ajax请求中，type:"GET"
    
    post方式：
        01：form表单中，method="POST"
        02：ajax请求中，type:"POST"

"""
def requestTest(request):
    # print(request)
    # print(type(request))

    # print(request.method) # 得到请求方法   GET  POST   PUT  DELETE

    # print(request.GET.get("id")) # 接收前台参数

    # print(request.FILES.get("filename"))  # 接收前台文件

    # 了解
    # print(request.path)  # 获取请求路由
    # print(request.path_info)  # 获取请求路由
    # print(request.encoding) # 编码
    # print(request.scheme)  # 请求协议
    # print(request.body)  # 请求体
    # print(request.get_port())  # 8000
    # print(request.get_host())  #localhost:8000
    # print(request.is_ajax()) # 当次请求是否是ajax

    return HttpResponse("lufei,海贼王,21")


"""
    01:转发render或重定向redirect
    02:直接通过HttpResponse响应普通字符串
    
    03:在02响应的基础之上，如果字符串有特殊格式（JSON格式），那么响应回去的数据可以做特殊处理
        响应JSON格式字符串
            方式一：手动拼接
            方式二：通过json模块将字典转换为json格式字符串 （需要导入： import json）
            方式三：通过JsonResponse  （需要导入：from django.http import JsonResponse）

"""
import json
from django.http import JsonResponse
def responseTest(request):

    #name = "{\"username\":\"lufei\",\"title\":\"海贼王\",\"age\":21}"

    name = {"username":"张三","password":"123456","address":"太原"}

    # return HttpResponse(json.dumps(name))
    return JsonResponse(name)

def jsontest(request):
    return render(request,"jsontest.html")


# urltest/?year=2025
# urltest/2025   路径传参   REST FULL风格
def urltest(request,year):
    print("路由系统测试")
    print(year,type(year))
    return render(request,"index.html")










